import Dexie from 'dexie';
import "dexie-export-import";

const db = new Dexie('hl-lowcode');

db.version(1).stores({
    form: "++id, formName, formDesc, content, createdAt, updatedAt",
});
db.version(3).stores({
    workflow: "++id, workflowName, formId, formName, bpmnContent, status, createdAt, updatedAt",
});

// form CRUD
export async function getForms() {
    console.log('DB: get forms')
    return await db.form.toArray()
}

export async function getForm(id) {
    console.log('DB: get form', id)
    const form = await db.form.get({ id: parseInt(id) })
    if (form) form.formEngine = 'GFORM'
    return form
}

export async function saveForm(form) {
    console.log('DB: save form', form)
    if (!form.createdAt) form.createdAt = new Date()
    if (form.createdAt) form.updatedAt = new Date()
    let id = await db.form.put(form)
    return {...form, id}
}

export async function deleteForm(id) {
    console.log('DB: delete form', id)
    return await db.form.where({ id }).delete()
}

// workflow CRUD
export async function getWorkflows() {
    console.log('DB: get workflows')
    return await db.workflow.toArray()
}

export async function getWorkflowsByStatus(status) {
    console.log('DB: get workflows by status')
    return await db.workflow.where({status}).toArray()
}

export async function getWorkflow(id) {
    console.log('DB: get workflow', id)
    return await db.workflow.get({ id: parseInt(id) })
}

export async function updateWorkflowContent({id, bpmnContent}) {
    console.log('DB: update workflow content')
    return await db.workflow.where({ id: parseInt(id) }).modify({ bpmnContent: bpmnContent.xml })
}

export async function saveWorkflow(workflow) {
    console.log('DB: save workflow', workflow)
    if (!workflow.status) workflow.status = '10'
    if (!workflow.createdAt) workflow.createdAt = new Date()
    if (workflow.createdAt) workflow.updatedAt = new Date()
    let id = await db.workflow.put(workflow)
    return {...workflow, id}
}

export async function deleteWorkflow(id) {
    console.log('DB: delete workflow', id)
    return await db.workflow.where({ id }).delete()
}

export async function publishWorkflow(workflow) {
    console.log('DB: delete workflow', id)
    return await db.workflow.put(workflow)
}

export async function withdrawWorkflow(id) {
    console.log('DB: delete workflow', id)
    return await db.workflow.where({ id }).modify({ status: '10' })
}

// export and import
export async function exportDB() {
    const tables = ['form']
    const blob = await db.export({
        prettyJson: true,
        filter: (table, value, key) => {
            return tables.includes(table)
        }
    });
    return blob
}

export async function importDB(blob) {
    await db.delete();
    await Dexie.import(blob, {
        
    });
}
